package jmetrix.et;

import jmetrix.group.GroupAspect;
import jmetrix.bus.impl.NamedBusFactory;
import org.aspectj.lang.ProceedingJoinPoint;

/**
 * @author Konstantin Kuzmin
 * @version $Revision$
 * @since 01.10.11
 */
//TODO abstract from AspectJ
//TODO add debug logging
public abstract class ExecutionTimeAspect extends GroupAspect {

    public static final String BUS_NAME = ExecutionTime.class.getName();

    @Override
    protected String getGroup(final ProceedingJoinPoint pjp) {
        return pjp.getClass().getName();
    }

    public Object measure(final ProceedingJoinPoint pjp) throws Throwable {
        return group(pjp);
    }

    public Object measureOnce(final ProceedingJoinPoint pjp) throws Throwable {
        if (!isInGroup(getGroup(pjp))) {
            return group(pjp);
        } else {
            return pjp.proceed();
        }
    }

    @Override
    protected Object proceed(final ProceedingJoinPoint pjp) throws Throwable {
        //TODO more certain timing source
        final long startTime = System.currentTimeMillis();
        final Object result = pjp.proceed();
        final long executionTime = (System.currentTimeMillis() - startTime);
        sendEvent(executionTime);
        return result;
    }
}
